package middle.ground.http.interceptor;

import middle.ground.utils.StringUtil;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 系统日志拦截器
 * <p>
 * 主要是为全链路日志追踪，错误排查做辅助
 * </p>
 *
 * @author jrl
 * @date 2020/3/31 09:06
 */
public class LogInterceptor extends HandlerInterceptorAdapter {
	/**
	 * 会话ID
	 */
	private final static String SESSION_KEY = "token";
	private final static String QUERY_MB = "queryMb";

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
		MDC.remove(SESSION_KEY);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("token");
		String queryMb = request.getParameter("_t");
		String replaceToken = UUID.randomUUID().toString().replace("-", "");
		MDC.put(SESSION_KEY, StringUtil.isBlank(token) ? "no_login_" + replaceToken : token);
		MDC.put(QUERY_MB, queryMb);

		return true;
	}
}
